import { useEffect, useState } from 'react'
import { Card, Form, Input, Button, Upload, message, Avatar } from 'antd'
import { UserOutlined, UploadOutlined } from '@ant-design/icons'
import { useSelector, useDispatch } from 'react-redux'
import { RootState } from '../../store'
import { userService } from '../../services'
import { updateUser } from '../../store/slices/authSlice'

const Profile = () => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const { user } = useSelector((state: RootState) => state.auth)
  const dispatch = useDispatch()

  useEffect(() => {
    loadProfile()
  }, [])

  const loadProfile = async () => {
    try {
      const response: any = await userService.getProfile()
      if (response.code === 200) {
        form.setFieldsValue(response.data.profile)
      }
    } catch (error) {
      console.error('Load profile error:', error)
    }
  }

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true)
      const response: any = await userService.updateProfile(values)
      if (response.code === 200) {
        message.success('资料更新成功!')
      }
    } catch (error) {
      console.error('Update profile error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleAvatarUpload = async (info: any) => {
    if (info.file.status === 'done') {
      const response = info.file.response
      if (response.code === 200) {
        message.success('头像上传成功!')
        dispatch(updateUser({ ...user!, avatar: response.data.avatar }))
      }
    }
  }

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', padding: '24px' }}>
      <Card title="个人资料">
        <div style={{ textAlign: 'center', marginBottom: '24px' }}>
          <Avatar size={100} src={user?.avatar} icon={<UserOutlined />} />
          <div style={{ marginTop: '16px' }}>
            <Upload
              name="avatar"
              action="/api/users/avatar"
              headers={{
                Authorization: `Bearer ${localStorage.getItem('token')}`,
              }}
              showUploadList={false}
              onChange={handleAvatarUpload}
            >
              <Button icon={<UploadOutlined />}>更换头像</Button>
            </Upload>
          </div>
        </div>

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="fullName"
            label="姓名"
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="bio"
            label="个人简介"
          >
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item
            name="education"
            label="学历"
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="occupation"
            label="职业"
          >
            <Input />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Profile
